<template>
  <div class="pandx">
    <Card dis-hover>
      <Tabs :value="currentElement.type">
        <TabPane label="流程属性" icon="md-git-network" name="area" :disabled="currentElement.type!=='area'">
          <div class="attr-content">
            <div class="attr-body">
              <Form ref="flowForm" :model="currentElement" label-position="top">
                <FormItem label="流程编号" prop="name">
                  <Input v-model="currentElement.name" disabled placeholder=""></Input>
                </FormItem>
              </Form>
            </div>
          </div>
        </TabPane>
        <TabPane label="节点属性" icon="md-list" name="node" :disabled="currentElement.type!=='node'">
          <div class="attr-content">
            <div class="attr-body">
          <Form ref="nodeForm" :model="currentElement.node" label-position="top" v-if="currentElement.node!==null">
            <FormItem label="节点编号" prop="id">
              <Input v-model="currentElement.node.id" disabled placeholder=""></Input>
            </FormItem>
            <FormItem label="节点类型" prop="typeName">
              <Input v-model="currentElement.node.typeName" disabled placeholder=""></Input>
            </FormItem>
            <FormItem label="节点名称" prop="name">
              <Input v-model="currentElement.node.name" :maxlength="64" placeholder="" clearable></Input>
            </FormItem>
            <FormItem label="执行权限">
              <Select :disabled="disableAllot" v-model="currentElement.node.info.allot" style="width:100%"
                      @on-open-change="clearFocus" @on-change="clearNodeInfo" placeholder="请选择节点执行权限">
                <Option v-for="item in allots" :value="item.value" :key="item.value">{{
                    item.label
                  }}
                </Option>
              </Select>
            </FormItem>
            <FormItem label="指定角色" prop="allotRoles" v-if="currentElement.node.info.allot==='DESIGNROLE'">
              <Input v-model="currentElement.node.info.roleText" readonly placeholder="" @on-focus="focusRole"
                     :disabled="!(currentElement.node.info.allot==='DESIGNROLE')" clearable @on-clear="clearDesignRole"></Input>
            </FormItem>
            <FormItem label="指定用户" prop="allotUsers" v-else>
              <Input v-model="currentElement.node.info.userText" readonly placeholder="" @on-focus="focusUser"
                     :disabled="!(currentElement.node.info.allot==='DESIGNUSER')" clearable @on-clear="clearDesignUser"></Input>
            </FormItem>
            <FormItem label="指定执行权限时限定在同一单位" prop="sameUnit">
              <i-switch v-model="currentElement.node.info.sameUnit"
                        :disabled="!(currentElement.node.info.allot==='RUNNINGUSER')"></i-switch>
            </FormItem>
            <FormItem label="指定执行权限时限定在以下角色" prop="restrictRoles">
              <Input v-model="currentElement.node.info.restrictRoleText" readonly placeholder=""
                     @on-focus="focusRestrictRole"
                     :disabled="!(currentElement.node.info.allot==='RUNNINGROLE' || currentElement.node.info.allot==='RUNNINGUSER')" clearable @on-clear="clearRestrictRole"></Input>
            </FormItem>
            <FormItem label="多人审批" prop="joinType">
              <Select v-model="currentElement.node.info.joinType" style="width:100%" @on-open-change="clearFocus"
                      placeholder="请选择多人审批方式"
                      :disabled="!((currentElement.node.info.allot==='DESIGNUSER' && currentElement.node.info.users.length>1) || currentElement.node.info.allot==='DESIGNROLE')">
                <Option v-for="item in joinTypes" :value="item.value" :key="item.value">{{
                    item.label
                  }}
                </Option>
              </Select>
            </FormItem>
            <FormItem label="抄送" prop="copy">
              <i-switch v-model="currentElement.node.info.copy" @on-change="changeCopy"
                        :disabled="!(currentElement.node.type==='task' && (currentElement.node.info.allot==='DESIGNUSER' || currentElement.node.info.allot==='DESIGNROLE'))"></i-switch>
            </FormItem>
            <FormItem label="抄送用户" prop="copyUsers">
              <Input v-model="currentElement.node.info.copyUserText" readonly placeholder=""
                     @on-focus="focusCopyUser" :disabled="!(currentElement.node.info.copy)" clearable @on-clear="clearCopyUser"></Input>
            </FormItem>
          </Form>
            </div>
          </div>
        </TabPane>
        <TabPane label="连线属性" icon="md-share" name="line" :disabled="currentElement!=='line'">
          <div class="attr-content">
            <div class="attr-body">
          <Form ref="linForm" :model="currentElement.line" label-position="top" v-if="currentElement.line!==null">
            <FormItem label="连线描述" prop="label">
              <Input v-model="currentElement.line.label" :maxlength="64" placeholder=""
                     @on-change="changeLabel" clearable></Input>
            </FormItem>
            <FormItem label="连线条件" prop="conditions">
              <Row v-for="(item,index) in currentElement.line.conditions" :key="index" :gutter="10">
                <Col span="10">
                  <FormItem>
                    <Select transfer filterable clearable placeholder=""
                            v-model="currentElement.line.conditions[index].field">
                      <Option v-for="item in fields" :value="item.key" :key="item.key">{{ item.label }}</Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="5">
                  <FormItem>
                    <Select transfer filterable clearable placeholder=""
                            v-model="currentElement.line.conditions[index].operation"
                            :disabled="!currentElement.line.conditions[index].field">
                      <Option value="=" :Key="1">=</Option>
                      <Option value=">" :Key="2">></Option>
                      <Option value=">=" :Key="3">>=</Option>
                      <Option value="<" :Key="4"><</Option>
                      <Option value="<=" :Key="5"><=</Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="6">
                  <FormItem>
                    <Input :maxlength="256" placeholder="" clearable
                           v-model="currentElement.line.conditions[index].value"
                           :disabled="!currentElement.line.conditions[index].field"></Input>
                  </FormItem>
                </Col>
                <Col span="3">
                  <FormItem>
                    <Button @click="addCondition" icon="md-add" shape="circle" v-if="index===0" type="success"
                            size="small"
                            :disabled="conditionIndex===9"></Button>
                    <Button @click="removeCondition(index)" icon="md-remove" shape="circle" v-if="index!==0"
                            type="warning" size="small"></Button>
                  </FormItem>
                </Col>
              </Row>
            </FormItem>
          </Form>
            </div>
          </div>
        </TabPane>
      </Tabs>
    </Card>
    <o-u-user-select-modal v-if="userSelectModalMount" v-model="userSelectModalShow"
                           @submit="obtainUsers" :modal-data="userSelectModalData"></o-u-user-select-modal>
    <role-select-modal v-if="roleSelectModalMount" v-model="roleSelectModalShow"
                       @submit="obtainRoles" :modal-data="roleSelectModalData"></role-select-modal>
  </div>
</template>

<script lang="ts">
import {Component, Vue, Prop, Watch, Emit} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';
import _ from 'lodash';
import OUUserSelectModal from '@/components/common-modal/o-u-user-select-modal.vue';
import RoleSelectModal from '@/components/common-modal/role-select-modal.vue';
import Condition from '@/store/entities/flow/flow-data/condition';

@Component({
  components: {RoleSelectModal, OUUserSelectModal},
})
export default class FlowAttr extends AbpBase {
  name: string = 'FlowAttr';

  @Prop({type: Object, default: {}}) currentElement: any;
  @Prop({type: Array, default: () => []}) fields: string[];

  conditionIndex: number = 0;

  allots = [
    {
      value: 'EVERYONE',
      label: '本系统任意用户',
    }, {
      value: 'DESIGNUSER',
      label: '设计时指定用户',
    }, {
      value: 'DESIGNROLE',
      label: '设计时指定角色',
    }, {
      value: 'RUNNINGUSER',
      label: '运行时指定用户',
    }, {
      value: 'RUNNINGROLE',
      label: '运行时指定角色',
    },
  ];
  joinTypes = [
    {
      value: 'ALL',
      label: '会签（所有审批人都处理才行）',
    }, {
      value: 'ANY',
      label: '或签（任一审批人处理后即可）',
    },
  ];

  userSelectModalMount: boolean = false;
  userSelectModalShow: boolean = false;
  userSelectModalData: any = {};

  roleSelectModalMount: boolean = false;
  roleSelectModalShow: boolean = false;
  roleSelectModalData: any = {};

  disableAllot: boolean = false;

  @Watch('currentElement')
  currentElementChange(newVal) {
    switch (newVal.type) {
      case 'node':
        if (newVal.node.type === 'start' || newVal.node.type === 'end') {
          this.currentElement.node.info.allot = 'EVERYONE';
          this.disableAllot = true;
        } else {
          this.disableAllot = false;
        }
        break;
    }
  }


  changeCopy(value: boolean) {
    if (!value) {
      this.currentElement.node.info.copyUsers = [];
      this.currentElement.node.info.copyUserText = '';
    }
  }

  changeLabel(event) {
    this.$emit('change', event, this.currentElement.line);
  }

  x(items: any[]) {
    let result: boolean = true;
    for (let i = 0; i < items.length; i++) {
      if (typeof (items[i]) !== 'number') {
        result = false;
      }
    }
    return result;
  }

  focusUser() {
    const users = _.cloneDeep(this.currentElement.node.info.users);
    if (this.x(users)) {
      this.userSelectModalData = {
        selectedUsers: users.map((item, index) => {
          return {id: item, name: this.currentElement.node.info.userText.split(',')[index]}
        }), opener: 1
      };
    } else {
      this.userSelectModalData = {selectedUsers: users, opener: 1};
    }
    this.userSelectModalMount = true;
    this.$nextTick(() => {
      this.userSelectModalShow = true;
    });
  }

  focusCopyUser() {
    const users = _.cloneDeep(this.currentElement.node.info.copyUsers);
    if (this.x(users)) {
      this.userSelectModalData = {
        selectedUsers: users.map((item, index) => {
          return {id: item, name: this.currentElement.node.info.copyUserText.split(',')[index]}
        }), opener: 2
      };
    } else {
      this.userSelectModalData = {selectedUsers: users, opener: 2};
    }
    this.userSelectModalMount = true;
    this.$nextTick(() => {
      this.userSelectModalShow = true;
    });
  }

  focusRole() {
    const roles = _.cloneDeep(this.currentElement.node.info.roles);
    if (this.x(roles)) {
      this.roleSelectModalData = {
        selectedRoles: roles.map((item, index) => {
          return {
            id: item,
            name: this.currentElement.node.info.roleText.split(',')[index],
            displayName: this.currentElement.node.info.roleText.split(',')[index]
          }
        }), opener: 1
      };
    } else {
      this.roleSelectModalData = {selectedRoles: roles,opener:1};
    }
    this.roleSelectModalMount = true;
    this.$nextTick(() => {
      this.roleSelectModalShow = true;
    });
  }

  focusRestrictRole() {
    const roles = _.cloneDeep(this.currentElement.node.info.restrictRoles);
    if (this.x(roles)) {
      this.roleSelectModalData = {
        selectedRoles: roles.map((item, index) => {
          return {
            id: item,
            name: this.currentElement.node.info.restrictRoleText.split(',')[index],
            displayName: this.currentElement.node.info.restrictRoleText.split(',')[index]
          }
        }), opener: 2
      };
    } else {
      this.roleSelectModalData = {selectedRoles: roles,opener:2};
    }
    this.roleSelectModalMount = true;
    this.$nextTick(() => {
      this.roleSelectModalShow = true;
    });
  }

  obtainUsers(selectedUsers: any, opener: number) {
    switch (opener) {
      case 1:
        this.currentElement.node.info.users = selectedUsers;
        this.currentElement.node.info.userText = selectedUsers.map(u => u.name).join(', ');
        if (this.currentElement.node.info.users.length <= 1) {
          this.currentElement.node.info.joinType = '';
        }
        break;
      case 2:
        this.currentElement.node.info.copyUsers = selectedUsers;
        this.currentElement.node.info.copyUserText = selectedUsers.map(u => u.name).join(', ');
        break;
    }
  }

  obtainRoles(selectedRoles: any,opener:number) {
    switch (opener) {
      case 1:
        this.currentElement.node.info.roles = selectedRoles;
        this.currentElement.node.info.roleText = selectedRoles.map(r => r.displayName).join(', ');
        break;
      case 2:
        this.currentElement.node.info.restrictRoles = selectedRoles;
        this.currentElement.node.info.restrictRoleText = selectedRoles.map(r => r.displayName).join(', ');
        break;
    }

  }

  clearFocus(value: boolean) {

    for (const element of this.$el.getElementsByClassName('ivu-select-item')) {
      element.classList.remove('ivu-select-item-focus');
    }
  }

  clearNodeInfo() {
    this.currentElement.node.info.joinType = '';
    this.currentElement.node.info.users = [];
    this.currentElement.node.info.userText = '';
    this.currentElement.node.info.roles = [];
    this.currentElement.node.info.roleText = '';
    this.currentElement.node.info.copy = false;
    this.currentElement.node.info.copyUsers = [];
    this.currentElement.node.info.copyUserText = '';
    this.currentElement.node.info.sameUnit = false;
  }

  addCondition() {
    this.conditionIndex++;
    this.currentElement.line.conditions.push(new Condition());
  }

  removeCondition(index: number) {
    this.conditionIndex--;
    this.currentElement.line.conditions.splice(index, 1);
  }

  clearDesignRole(){
    this.currentElement.node.info.roleText='';
    this.currentElement.node.info.roles=[];
  }
  clearDesignUser(){
    this.currentElement.node.info.userText='';
    this.currentElement.node.info.users=[];
  }
  clearRestrictRole(){
    this.currentElement.node.info.restrictRoleText='';
    this.currentElement.node.info.restrictRoles=[];
  }
  clearCopyUser(){
    this.currentElement.node.info.copyUserText='';
    this.currentElement.node.info.copyUsers=[];
  }


}
</script>

<style lang="less" scoped>
.pandx::v-deep .attr-content .attr-body{
  overflow: auto;
  height:calc(100vh - 359px);
  padding: 6px 12px;
}
.pandx::v-deep .attr-content .attr-body::-webkit-scrollbar {
  width: 4px;
  background-color: #fff;
}

.pandx::v-deep .attr-content .attr-body::-webkit-scrollbar-thumb {
  border-radius: 2px;
  -webkit-box-shadow: inset 0 0 1px rgba(0, 0, 0, .3);
  background-color: #e8eaec;
}

.pandx::v-deep .attr-content .attr-body::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 1px rgba(0, 0, 0, .3);
  border-radius: 2px;
  background-color: #fff;
}
</style>
